package compress

// 仅限linux环境下使用
import (
	"archive/zip"
	"bytes"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"

	"qb/l"
	"sora/scan"
)

const (
	SRC_ROOT = "../dataSrc/" // .../bid/vid.sln
	DST_ROOT = "../dataDst/" // .../vid/
)

func Walk(count int) {
	vpaths := make([]string, 0)
	filepath.Walk(SRC_ROOT, func(path string, info os.FileInfo, err error) error {
		if strings.HasSuffix(path, ".sln") {
			vpaths = append(vpaths, path)
		}
		return nil
	})
	fmt.Println(len(vpaths))
	ch := make(chan bool, len(vpaths))
	runtime.GOMAXPROCS(16)
	for _, path := range vpaths {
		//time.Sleep(time.Millisecond * 200)
		go RunUnzip(path, ch)
		//unzip(path)
	}
	for i := 0; i < len(vpaths); i++ {
		<-ch
	}
}

// 对unzip的并发封装
func RunUnzip(path string, ch chan bool) {
	// go func(ch chan bool) { // timeout
	// 	time.Sleep(time.Second * 40)
	// 	ch <- false
	// 	fmt.Println(path)
	// }(ch)
	unzip(path)
	ch <- true
}
func unzip(path string) {
	rc, err := zip.OpenReader(path)
	l.Debug(err)
	defer rc.Close()
	vid := regexp.MustCompile("(\\d+).sln$").FindStringSubmatch(path)[1]
	os.MkdirAll(DST_ROOT+vid+"/content/", 0764)
	os.MkdirAll(DST_ROOT+vid+"/img/", 0764)

	for _, f := range rc.File {
		src, _ := f.Open()
		if f.FileInfo().Size() == 0 {
			continue
		}
		//dataType := regexp.MustCompile("(\\w+)\\/").FindStringSubmatch(f.FileInfo().Name())[1]
		isImg := len(f.FileInfo().Name()) == 32
		if isImg {
			dst, err := os.Create(DST_ROOT + vid + "/img/" + strings.ToLower(f.FileInfo().Name()) + ".jpg")
			l.Debug(err)
			io.Copy(dst, src)
		} else {
			if f.FileInfo().Name() == "Package" { // 忽略Package.json
				continue
			}
			dst, err := os.Create(DST_ROOT + vid + "/content/" + strings.ToLower(f.FileInfo().Name()) + ".json")
			l.Debug(err)
			// 转换
			dText, err := translate(src, vid)
			l.Debug(err)
			io.Copy(dst, bytes.NewReader(dText))
		}
	}
	//fmt.Println(vid)
}
func translate(src io.Reader, vid string) ([]byte, error) {
	// file to []byte
	b := bytes.NewBuffer(nil)
	_, err := b.ReadFrom(src)
	l.Debug(err)
	// 根据换行符分割，得出包含每段内容的字符串数组
	lines := strings.Split(string(b.Bytes()), "\n")
	divs := make([]scan.Div, 0)

	//FindStringSubmatch() 返回[1]为type，[2]为内容
	re := regexp.MustCompile("\\{\\{(T|I)\\}\\}(.+)")
	for i, line := range lines {
		div := re.FindStringSubmatch(line)
		if len(div) > 2 {
			d := &scan.Div{}
			d.Id = i
			if div[1] == "T" {
				d.T = 0
				d.C = div[2]
			} else {
				d.T = 1
				h := md5.New()
				io.WriteString(h, div[2])
				md := fmt.Sprintf("%x", h.Sum(nil))
				d.C = "/" + vid + "/img/" + md + ".jpg"
			}
			divs = append(divs, *d)
		}
	}
	return json.Marshal(divs)
}
